<template>
  <div class="alarm-wrap">
    <div class="info-box" @click="showInfo">
      <img
        v-if="$route.path == '/cameraPlay' || $route.path == '/videoRecord'"
        src="~assets/img/alarm_cameraPlay.png"
      />
      <img v-else src="~assets/img/alarm.png" />
      <span class="alarmNum">{{ alertInfoArr.length }}</span>
    </div>
    <div
      class="alert-box"
      v-if="
        alertInfoShow && Array.isArray(alertInfoArr) && alertInfoArr.length > 0
      "
    >
      <!--初始显示-->
      <el-alert
        :title="alertInfoArr[0].datas.title"
        :type="alertInfoArr[0].datas.type == 2 ? 'success' : 'info'"
        :description="formatTime(alertInfoArr[0].datas.ts)"
        show-icon
        @close="close_alart"
      >
      </el-alert>
    </div>
    <!--点击显示全部-->
    <div class="click-box" v-if="click_alert_show">
      <div class="message-box">
        <el-alert
          show-icon
          v-for="(item, index) in alertInfoArr"
          :key="index"
          :type="item.datas.type == 2 ? 'success' : 'info'"
          :description="formatTime(item.datas.ts)"
          @close="close_alart"
        >
          <div slot="title">
            {{item.datas.title}}
            <el-button class="smallBtn" v-if="item.datas.action" type="primary" size="mini" @click="fnPlay(item)">播放</el-button>
          </div>
        </el-alert>
      </div>

      <div class="btn-wrap-fixed">
        <el-button
          type="primary"
          plain
          size="mini"
          class="clear_arr"
          @click="clear_arr"
          >清空</el-button
        >
        <el-button
          type="primary"
          plain
          size="mini"
          class="close_arr"
          @click="close_arr"
          >关闭</el-button
        >
      </div>
    </div>
    <Telport to="body">
      <el-dialog
          :title="title"
          :visible.sync="showModal"
          :close-on-click-modal="false"
          :before-close="fnClose"
          width="60%">
        <!--        <video controls style="position:relative;z-index:9999;width: 100%;height: 100%;" src="http://f.video.weibocdn.com/o0/ufOkLKY4lx083bVkNbmo01041202j50I0E010.mp4?label=mp4_hd&template=852x480.25.0&media_id=4869755308539960&tp=8x8A3El:YTkl0eM8&us=0&ori=1&bf=2&ot=h&ps=3lckmu&uid=3ZoTIp&ab=,8143-g0,8013-g0,3601-g33,7598-g0&Expires=1677077548&ssig=3Ywug489Nx&KID=unistore,video"></video>-->
        <div class="videoWrap">
          <!--ws://52.131.47.150:46000/live/000.flv?tik=224a121104154429137864d5821ac6a1&tikpwd=-->
          <video-ws v-if="videoShow" style="position:relative;z-index:9999;width: 100%;height: 100%;" :url="stream"></video-ws>
        </div>
      </el-dialog>
    </Telport>
  </div>
</template>

<script>
//https://www.cnblogs.com/qisi007/p/10213886.html
import { getYMDHMS } from "@/utils/Tool";
import {postData} from "@/request/http";
import Telport from "./Telport";
import VideoWs from "./Video";
window.reStartStatus = true;
export default {
  name: "Alarm",
  components: {VideoWs, Telport},
  data() {
    return {
      alertInfoArr: [
        // {
        //   datas: {
        //     ts: new Date().getTime(),
        //     msg: "测试1",
        //     title: "测试1",
        //     sn: "YDT-ONVIF-70570842525051-50069800",
        //     action: "AI_HUO",
        //   }
        //
        // },
        // {
        //   datas: {
        //     ts: new Date().getTime(),
        //     msg: "测试2",
        //     title: "测试2",
        //     sn: "YDT-ONVIF-70570842525051-50069801",
        //     action: "AI_HUO",
        //   }
        // }
      ],  // 测试数据，测试完成清空

      path: "",
      socket: null,
      timer: null,
      reStartStatus: true,
      alertInfoShow: false,
      click_alert_show: false,
      stream: "",
      title: "",
      showModal: false,
      videoShow: false
    };
  },
  mounted() {
    // let _path = window.baseUrl + "websocket";
    // let _path = 'http://192.168.1.77:8080/websocket'
    // if (_path.indexOf("https") == 0) {
    //   let path_https = _path.replace(/https/g, "ws");
    //   this.path = path_https;
    // } else {
    //   let path_http = _path.replace(/http/g, "ws");
    //   this.path = path_http;
    // }
    if (process.env.NODE_ENV === "development") {
      this.path = 'ws://ydts3.hbwlife.com/websocket';
    } else if (process.env.NODE_ENV === "production") {
      this.path = "ws://" + window.location.host+"/websocket";
    }

    this.initWs();

    if (window.mysocket) {
      window.reStartStatus = false;
      window.mysocket.close();
      if (window.timerWs) {
        clearInterval(window.timerWs);
      }
      this.initWs();
    } else {
      if (window.timerWs) {
        clearInterval(window.timerWs);
      }
      this.initWs();
    }
  },
  computed: {
    username() {
      return this.$store.state.login.username;
    },
  },
  methods: {
    //初始ws
    initWs() {
      let that = this;
      window.mysocket = null;
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        window.mysocket = that.socket = new WebSocket(that.path);
        // 监听socket连接
        window.mysocket.onopen = that.open;
        // 监听socket错误信息
        window.mysocket.onerror = that.error;
        // 监听socket消息
        window.mysocket.onmessage = that.getMessage;
        // 关闭 socket消息
        window.mysocket.onclose = that.close;
      }
    },
    open() {
      console.log("WS connected!");
      this.send();
    },
    send() {
      window.mysocket.send(
        JSON.stringify({
          action: "sys/websocket/register",
          user_name: localStorage.getItem("username"),
          token: localStorage.getItem("token"),
          datas: {
            session_id: new Date().getTime(),
          },
        })
      );
    },
    getMessage(msg) {
      let nowMsg = JSON.parse(msg.data);
      if (nowMsg.connection == "close") {
        window.reStartStatus = false;
        if (window.timerWs) {
          clearInterval(window.timerWs);
        }
        window.mysocket.close();
        return;
      }
      if (nowMsg.action == "sys/websocket/register" && nowMsg.code == 0) {
        window.wsTime = nowMsg.datas.heartbeat_interval;
        this.heartWs();
      }
      if (nowMsg.action == "device/status/changed" && nowMsg.code == 0) {
        nowMsg.title = nowMsg?.datas?.msg || '';
        nowMsg.ts = nowMsg.datas.ts;
        this.alertInfoArr.unshift(nowMsg);
        this.alertInfoShow = true;
        var timer;
        if (timer) {
          clearTimeout(timer);
        }

        timer = setTimeout(() => {
          this.alertInfoShow = false;
        }, 3000);
      }

      //新需求
      //在该ws的消息列表里面，需要做些判断，如果action='device/general/message' 并且 datas.action='AI_FIRE' 或 'AI_SMOKE' 时，
      // 加一个查看视频的按钮，点击查看视频就弹窗播放视频。这个弹窗和那个自动弹窗是分开的。
      if (nowMsg.action == "device/general/message" && nowMsg.code == 0) {
        if(nowMsg.datas.action == "AI_FIRE" || nowMsg.datas.action == "AI_SMOKE"){
          nowMsg.title = nowMsg?.datas?.title || '';
          nowMsg.ts = nowMsg.datas.ts;
          nowMsg.sn = nowMsg.datas.sn;
          nowMsg.action = nowMsg.datas.action
          this.alertInfoArr.unshift(nowMsg);
        }

      }
    },
    close() {
      console.log("WS Closed!");
      if (window.timerWs) {
        clearInterval(window.timerWs);
      }
      if (window.mysocket && window.reStartStatus) {
        this.initWs(); //断开、刷新后重连
      }
    },
    error() {
     // console.log("connecte fail");
    },
    /* 
    心跳服务
    */
    heartWs() {
      if (window.mysocket && window.wsTime) {
        window.timerWs = setInterval(() => {
          window.mysocket.send(
            JSON.stringify({
              action: "ping",
              user_name: localStorage.getItem("username"),
              token: localStorage.getItem("token"),
            })
          );
        }, window.wsTime * 1000);
      }
    },

    // 播放
    async fnPlay(data){
      let sn = data.datas.sn
      if(sn){
        let datas = await postData("/adminweb/device/stream/live/url/ticket/lasted/unlimited", {
          sn: sn,
          ptl: "WS-FLV",
          sub: 0,
        })
        this.stream = datas?.datas?.stream || ""
        this.title = data.title
        if(!this.showModal){
          this.showModal = true
          setTimeout(()=> {
            this.videoShow = true
          }, 1000)
        }
        else{
          this.videoShow = false
          setTimeout(()=> {
            this.videoShow = true
          }, 1000)
        }
      }
    },

    // 弹窗关闭
    fnClose(){
      this.videoShow = false
      this.showModal = false
    },

    //点击的时候显示消息弹窗
    showInfo() {
      if (this.alertInfoArr.length > 0) {
        this.click_alert_show = true; //显示，点击弹窗
      }
    },

    //关闭 弹窗
    close_alart() {
      this.click_alert_show = false;
    },
    //清空按钮
    clear_arr() {
      // sessionStorage.clear();
      this.click_alert_show = false;
      this.alertInfoArr = [];
    },
    //关闭按钮
    close_arr() {
      this.click_alert_show = false;
    },
    //格式时间
    formatTime(time) {
      return getYMDHMS(time);
    },
    beforeMountbe() {
      this.click_alert_show = false;
    },
    destroyed() {
      this.click_alert_show = false;
    },
  },
  comments: {
    VideoWs,
    Telport
  }
};
</script>

<style scoped>
.alarm-wrap {
  width: 20px;
  height: 20px;
  float: left;
}
.alarm-wrap img {
  width: 100%;
  height: 100%;
}
.info-box{
  position: relative;
}
.alarmNum {
  background-color: #da2727;
  position: absolute;
  right: -10px;
  top: -8px;
  width: auto;
  height: auto;
  line-height: 17px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  border-radius: 50%;
  /* padding:2px; */
  padding: 2px 6px;
}
.alert-box {
  position: absolute;
  right: 0;
  width: auto;
  min-width: 500px;
  height: auto;
  display: flex;
  flex-flow: column;
  justify-content: flex-start;
  align-items: center;
  padding: 20px;
  /* background:rgb(0, 0, 0, 0.3);
  border-radius:10px; */
}
.click-box {
  position: absolute;
  top: 0;
  right: 0;
  width: 500px;
  height: auto;
  max-height: 600px;
  /* overflow-y:scroll; */
  display: -ms-flexbox;
  -ms-flex-flow: column;
  -ms-flex-pack: start;
  -ms-flex-align: center;
  padding: 20px;
  padding-top: 50px;
  background: #f7fbf7;
  border-radius: 10px;
  overflow: hidden;
}
.message-box {
  width: 100%;
  /* height: 500px; */
  height: auto;
  overflow-y: scroll;
}
/* .btn-wrap-fixed{
    position:fixed;
    top:0;
    right:0;
} */
.clear_arr {
  position: absolute;
  right: 90px;
  top: 8px;
}
.close_arr {
  position: absolute;
  right: 20px;
  top: 8px;
}
.alert-box >>> .el-alert {
  margin-bottom: 10px;
}
/* .alert-box >>> .el-alert--error.is-light .el-alert__description {
  color:#898b8e;
}
.alert-box >>> .el-alert.is-light .el-alert__closebtn {
  color:#000;
  font-size:14px;
}
.alert-box >>> .el-alert__title{
    color:rgb(199, 42, 42);
}
.alert-box >>> .el-alert__icon.is-big{
    color:rgb(199, 42, 42);
} */

.alert-box >>> .el-alert.is-light .el-alert__closebtn {
  opacity: 0;
}
.click-box >>> .el-alert.is-light .el-alert__closebtn {
  opacity: 0;
}
.smallBtn{
  width: 40px;
  height: 25px;
  padding: 0;
}
.videoWrap{
  width: 100%;
  height: 100%;
  background-color: #000;
}
</style>
